package top.huxy.web.config.interceptor;

import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.StringJoiner;

/**
 * @author aproz
 * @Date 2022/2/24
 */
public class CrosInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //设置允许任意域名访问
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, request.getHeader("Origin"));
        //允许请求方法
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST,GET");
        //允许携带cookie
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");

        //设置允许的请求头。
        StringJoiner allowedHeaders = new StringJoiner(",");
        allowedHeaders.add(HttpHeaders.AUTHORIZATION);
        allowedHeaders.add(HttpHeaders.ACCEPT);
        allowedHeaders.add(HttpHeaders.ORIGIN);
        allowedHeaders.add(HttpHeaders.USER_AGENT);
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, allowedHeaders.toString());

        //设置前端能拿到的请求头
        StringJoiner exposedHeaders = new StringJoiner(",");
        exposedHeaders.add("Remake");
        exposedHeaders.add(HttpHeaders.CONTENT_DISPOSITION);
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeaders.toString());
        return true;
    }
}